package com.ershui.blog.article.controller;

import com.ershui.blog.article.domain.CommonIds;
import com.ershui.blog.article.domain.LArticle;
import com.ershui.blog.article.domain.SelectArticleDto;
import com.ershui.blog.article.service.LArticleService;
import com.ershui.blog.system.controller.BaseController;
import com.ershui.blog.system.domain.AjaxResult;
import com.ershui.blog.system.domain.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Autowired
    private LArticleService articleService;

    @PostMapping("/add")
    public AjaxResult AddArticle(LArticle article){
        try{
            article.setCreateTime(new Date());
            articleService.insertSelective(article);
            return  AjaxResult.sucess();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/select")
    @ResponseBody
    public TableDataInfo SelectArticle(){
        startPage();
        List<SelectArticleDto> articleList=articleService.selectArticleList(null);
        return getDataTable(articleList);
    }


    @DeleteMapping("/delete")
    public AjaxResult DeleteArticle(@RequestBody  CommonIds ids){
        if(ids.getIds()!=null&&ids.getIds().size()>0){
            Map<String,Object> param=new HashMap<>();
            param.put("ids",ids.getIds());
            articleService.deleteArticles(param);
            return AjaxResult.sucess("删除成功");
        }else{
            return AjaxResult.error("删除失败，未勾选要删除数据");
        }
    }

    @GetMapping("/selectById")
    public AjaxResult SelectArticleById(Long id){
        LArticle article=articleService.selectArticleById(id);
        return  AjaxResult.sucess("查询成功",article);
    }


    @PutMapping("/update")
    public  AjaxResult UpdateArticleById(@RequestBody LArticle article){
        try{
            articleService.updateArticle(article);
            return AjaxResult.sucess();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
}
